<?php


namespace App\Services;

use App\Tools\CurlTools;
use App\Tools\JsonTools;
use App\Tools\RedisTools;
use Illuminate\Support\Facades\Config;
use Tencent\TLSSigAPIv2;
use Illuminate\Support\Env;
use function Swoole\Coroutine\Http\post;

include_once(Env::get('root_path') .'../vendor/tls-sig-api-v2-php/src/TLSSigAPIv2.php');#进行引入腾讯云即时通讯SDK
class IMServices
{
    protected $APPID = '';      #SDKID
    protected $AppSecret = '';   #SDK秘钥
    protected $Identifier = '';   #管理员账号
    protected $UserSig = '';   #管理员账号的密码
    protected $IMAccountImportUrl; #单个导入账号的url
    protected $IMAccountCheckUrl; #查询账号的url
    protected $IMPortraitSetUrl; #设置资料的url
    protected $IMPortraitGetUrl; #拉取资料的url
    protected $IMCreateGroupUrl; #创建群组url
    protected $IMsendFriendMessageUrl;#发送单聊消息
    protected $IMSendGroupMessageUrl; #发送群组自定义消息url
    protected $IMDownloadHistoryUrl; #下载最近消息记录url
    protected $IMSendGroupGlobalMessageUrl; #发送群组全局消息
    protected $IMsearchMessageUrl;


    public function __construct()
    {
        $this->APPID = Config::get('tencent.AppID');
        $this->AppSecret = Config::get('tencent.AppSecret');
        $this->Identifier = Config::get('tencent.Identifier');
//        $this->UserSig = Config::get('tencent.UserSig');
        //先进行从redis中取出管理员的userSig
        $redis = RedisTools::getInstance()->connectRedis();
        $userSig = $redis->get('fanyu_im_id_' . $this->Identifier);
//        //如果为空，则进行生成并且存入到redis
        if (empty($identifier)) {
            $userSig = $this->getSign($this->Identifier);
            $redis->set('fanyu_im_id_' . $this->Identifier, $userSig, 86400 * 175);
        }
        $this->UserSig = $userSig;
    }


    /**
     * 创建IM账号
     * @param $user
     * @return
     */

    public function accountImport($user)
    {
        //账号IM导入URL
        $this->IMAccountImportUrl = sprintf(
            config('tencent.im_url'), 'im_open_login_svc', 'account_import', $this->APPID, $this->Identifier, $this->UserSig, rand(1, 88888888));
        $params = [
            'Identifier' => $user->im_id,
            'Nick' => $user->user_name,
            'FaceUrl' => $user->user_image
        ];

        $result = CurlTools::curl_post($this->IMAccountImportUrl, $params);
        $result = json_decode($result, true);
        if ($result['ErrorCode'] != 0) {
            return false;
        }else {
            return true;
        }
    }


    /**
     * 设置资料&修改资料同步到腾讯云IM
     * 目前只有昵称和头像
     */
    public function portraitSet($user)
    {
//        还未生成签名
        $this->IMPortraitSetUrl = sprintf(
            config('tencent.im_url'), 'profile', 'portrait_set', $this->APPID, $this->Identifier, $this->UserSig, rand(1, 88888888));
        $params = [
            "From_Account" => $user->im_id,
            "ProfileItem" =>
                [
                    [
                        "Tag" => "Tag_Profile_IM_Nick",
                        "Value" => $user->user_name
                    ],
                    [
                        "Tag" => "Tag_Profile_IM_Image",
                        "Value" => $user->user_image
                    ]
                ]
        ];

        $result = CurlTools::curl_post($this->IMPortraitSetUrl, $params);
        $result = json_decode($result, true);
        if ($result['ErrorCode'] != 0) {
            return false;
        }else {
            return true;
        }
    }


    /**
     * @param $identifier 腾讯IM内部 ID，
     * @param float|int $expire 过期时间

     */
    public function getSign($identifier, $expire = 86400 * 180)
    {
        $obj = new TLSSigAPIv2($this->APPID, $this->AppSecret);
        try {
            $userSig = $obj->genSig($identifier);
            return $userSig;
        } catch (\Exception $e) {
            return false;
        }
    }

    /**
     * 单独发送消息
     */

    public function openIM($user){
        $this->IMsendFriendMessageUrl = sprintf(
            config('tencent.im_url'), 'openim', 'sendmsg', $this->APPID, $this->Identifier, $this->UserSig, rand(0, 4294967295));

//        $mycontent = [
//            "MsgType"=>$user['type'],
//            "MsgContent"=>['Text'=>$user['content']]
//
//        ];

        $params = [
            "SyncOtherMachine"=> 1,
            "From_Account"=> $user['send'],
            "To_Account"=>$user['receive'],
            "MsgRandom"=>rand(1111111, 9999999),
            "MsgBody"=>[
                [
                    "MsgType"=>$user['type'],
                    "MsgContent"=>['Text'=>$user['content']]
                ]


            ],
            "CloudCustomData"=>"your cloud custom data"

        ];

        $result = CurlTools::curl_post($this->IMsendFriendMessageUrl, $params);
        $result = json_decode($result, true);

        if ($result['ActionStatus'] == 'OK') {
            return true;
        }else{
            return false;
        }

    }

    /**
     * 查询单聊消息
     */

    public function searchMessage($user){

        $this->IMsearchMessageUrl = sprintf(
            config('tencent.im_url'), 'openim', 'admin_getroammsg', $this->APPID, $this->Identifier, $this->UserSig, rand(0, 4294967295));

        $params = [
            "Operator_Account"=> $user['my_id'],
            "Peer_Account"=>$user['you_id'],
            "MaxCnt"=>20,
            "MinTime"=>strtotime(date('Y-m-d')),
            "MaxTime"=>time()
        ];

        $result = CurlTools::curl_post($this->IMsearchMessageUrl, $params);
        $result = json_decode($result, true);

        if ($result['ActionStatus'] == 'OK') {
            return $result['MsgList'];
        }else{
            return false;
        }
    }






}
